﻿using AhpilyServer;
using PokerServer.Cache;
using PokerServer.Cache.Match;
using Protocol.Code;
using Protocol.Dto;
using System;

namespace PokerServer.Logic
{
    public class ChatHandler : IHandler
    {
        private UserCache userCache = Caches.User;
        private MatchCache matchCache = Caches.Match;

        public void OnDisconnect(ClientPeer client)
        {
        }

        public void OnReceive(ClientPeer client, int subCode, object value)
        {
            switch (subCode)
            {
                case ChatCode.CREQ:
                    ChatRequest(client, (int) value);
                    break;
                default:
                    Console.WriteLine("ChatHandler Have some wrong");
                    break;
            }
        }


        /// <summary>
        /// 处理聊天请求的方法
        /// </summary>
        /// <param name="client">请求者</param>
        /// <param name="chatType">请求内容</param>
        private void ChatRequest(ClientPeer client, int chatType)
        {
            if (userCache.IsOnline(client) == false)
            {
                return;
            }

            int userId = userCache.GetId(client);

            ChatDto dto = new ChatDto(userId, chatType);

            if (matchCache.IsMatching(userId))
            {
                MatchRoom matchRoom = matchCache.GetRoom(userId);

                matchRoom.Brocast(OpCode.CHAT, ChatCode.SRES, dto);
            }
            else if (false)
            {
                // TODO: 在这里检测战斗房间
            }
        }
    }
}